package com.bing.services.impl;

import com.bing.Component.Context;
import com.bing.bean.Tpp.BaiduWeather;
import com.bing.bean.weixin.ResponseMessage;
import com.bing.utils.CommonUtils;
import com.bing.utils.HttpUtils;
import com.bing.utils.MsgHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by Administrator on 2014/12/13.
 */
@Service
public class BaiduWeatherServiceImpl extends AbstractCommandService {

    protected int order = 100;
    private static final String ak = "l04DmoVrHOGfQ5R3c7RjyhGz";
    private static final String url = "http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=" + ak; //百度天气API
    private static final String TWTQ = TW + "天气";
    private static List<String> contexts = new ArrayList<String>() {
        {
            add(TWTQ);
        }
    };

    private Logger logger = LoggerFactory.getLogger(BaiduWeatherServiceImpl.class);

    @Override
    public ResponseMessage handle(Context context) {
        if (!StringUtils.hasText(context.getRequestMessage().getContent()) || "?".equals(context.getRequestMessage().getContent())
                || "？".equals(context.getRequestMessage().getContent())) {
            return MsgHelper.toText(context.getRequestMessage(), "请输入正确的城市!");
        }
        logger.debug("百度天气");
        String command = context.getRequestMessage().getContent();
        try {
            command = URLEncoder.encode(command, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String getUrl = String.format(url, command);
        String result = HttpUtils.get(getUrl);
        BaiduWeather baiduWeather = CommonUtils.baiduWeather().fromJson(result, BaiduWeather.class);
        ResponseMessage responseMessage = null;
        if (baiduWeather.getError() == 0) {
            responseMessage = MsgHelper.toNews(context.getRequestMessage(), baiduWeather.toArticles());
        } else {
            responseMessage = MsgHelper.toText(context.getRequestMessage(), "请输入正确的城市!");
        }
        return responseMessage;
    }

    @Override
    protected List<String> getContexts() {
        return contexts;
    }

    @Override
    protected Logger getLogger() {
        return logger;
    }


}
